package com.interaction.qualitytimeaiagent.app;

import com.interaction.qualitytimeaiagent.advisor.MyloggerAdvisor;
import com.interaction.qualitytimeaiagent.advisor.ReReadingAdvisor;
import com.interaction.qualitytimeaiagent.chatmemory.FileBasedChatMemory;
import com.interaction.qualitytimeaiagent.rag.QualityTimeRagCustomAdvisorFactory;
import com.interaction.qualitytimeaiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.MessageAggregator;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
//@Slf4j
public class QualityTimeApp {
    private static final Logger log = LoggerFactory.getLogger(QualityTimeApp.class);

    private final ChatClient client;
    private final String SYSTEM_PROMPT = "扮演深耕亲子互动以及新手宝妈指导领域的专家，开场向用户表明身份，告知用户可倾诉有关于亲子互动或者宝妈经验的难题，" +
            "围绕高质量亲子互动与游戏力提升,宝妈自我关怀与情绪管理,婴幼儿常见问题与规律养成,三个重点议题分析和提供对应的专属解决方案,解决方案要具体可操作。" +
            "可以想到情绪支持、实操方法和资源整合这三个方向,解决方案要分步骤，提供具体行动建议，比如情绪管理的AEC法则、游戏设计的SMILE法则，这样用户能直接落地执行," +
            "最后可以加入互动邀请，鼓励用户进一步交流，增强APP的粘性。整体结构可以按照欢迎语、三个议题展开、专属方案、结束语的顺序来组织";

    /**
     * 初始化客户端
     * 扮演深耕亲子互动以及新手宝妈指导领域的专家，开场向用户表明身份，告知用户可倾诉有关于亲子互动或者宝妈经验的难题，围绕高质量亲子互动与游戏力提升,宝妈自我关怀与情绪管理,婴幼儿常见问题与规律养成,三个重点议题分析和提供对应的专属解决方案
     * 解决方案要具体可操作。可以想到情绪支持、实操方法和资源整合这三个方向,解决方案要分步骤，提供具体行动建议，比如情绪管理的AEC法则、游戏设计的SMILE法则，这样用户能直接落地执行,
     * 最后可以加入互动邀请，鼓励用户进一步交流，增强APP的粘性。整体结构可以按照欢迎语、三个议题展开、专属方案、结束语的顺序来组织.
     *
     * @param dashscopeChatModel
     */
    public QualityTimeApp(ChatModel dashscopeChatModel) {
        //初始化基于内存的对话记忆
//        ChatMemory chatMemory=new InMemoryChatMemory();

        //基于文件的会话记忆
        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        client = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT).defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
//                        new SimpleLoggerAdvisor()
                        new MyloggerAdvisor()
//                       , new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * 基础对话,支持多轮对话记忆
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = client.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }

    //java21快速定义类
    record QualityTimeReport(String title, List<String> suggestions) {

    }

    /**
     * 亲子互动报告功能,结构化输出
     *
     * @param message
     * @param chatId
     * @return
     */
    public QualityTimeReport doChatWithReport(String message, String chatId) {
        QualityTimeReport entity = client.prompt()
                .system("每次对话后都要生成亲子互动结果,标题为{用户名}的亲子互动报告,内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(QualityTimeReport.class);
        log.info("QualityTimeReport:{}", entity);
        return entity;
    }

    //亲子互动知识库问答功能
    @Resource
    private VectorStore qualityTimeVectorStore;
    @Resource
    private Advisor qualityTimeRagCloudAdvisor;

    @Resource
    private VectorStore pgVectorVectorStore;
    @Resource
    private QueryRewriter queryRewriter;

    /**
     * RAG知识库对话
     *
     * @param message
     * @param chatId
     * @return
     */
    public String dochatwithRag(String message, String chatId) {
        //查询重写
        String rewrittenMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = client.prompt()
                .user(rewrittenMessage).advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyloggerAdvisor())
                //RAG知识库问答
                .advisors(new QuestionAnswerAdvisor(qualityTimeVectorStore))
                //RAG检索增强服务(基于云知识库服务)
//                .advisors(qualityTimeRagCloudAdvisor)
                //RAG检索增强服务(基于PgVector向量存储)
//                .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                //应用自定义RAG检索增强服务(文档查询器+上下文增强器)
//                .advisors(QualityTimeRagCustomAdvisorFactory.createQueryTimeRagCustomerAdvisor(qualityTimeVectorStore,"亲子"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }

    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = client
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))

                .advisors(new MyloggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
}
